const db = require("../db/index");

// 获取文章分类
exports.getArtCates = (req, res) => {
  let sqlStr =
    "select * from ev_article_cate where is_delete=0 order by id asc";
  db.query(sqlStr, (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: "0",
      message: "获取文章分类成功！",
      data: results,
    });
  });
};

// 新增文章分类
exports.addArtCates = (req, res) => {
  let { name, alias } = req.body;
  // 查重
  let sqlStr = "select * from ev_article_cate where name = ? or alias = ?";
  db.query(sqlStr, [name, alias], (err, results) => {
    if (err) return res.cc(err);
    // 这个地方可以做更多的判断，判读是别名还是名字重复或者双双重复
    if (results.length !== 0) {
      return res.send({
        status: "0",
        message: "分类名或者别名被占用！",
      });
    }
    // 新增操作
    sqlStr = "insert into ev_article_cate set ?";
    db.query(sqlStr, { name, alias }, (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) {
        return res.send({
          status: "1",
          message: "新增文章分类失败！",
        });
      }
      res.send({ status: "0", message: "新增文章分类成功！", data: results });
    });
  });
};

// 删除文章分类
exports.delectArtCates = (req, res) => {
  console.log(id);
  let sqlStr = "update ev_article_cate set is_delete = 1 where id = ?";
  db.query(sqlStr, id, (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) {
      return res.send({ status: "1", message: "删除文章分类失败！" });
    }
    res.send({
      status: "0",
      message: "删除文章分类数据成功！",
      data: results,
    });
  });
};

// 获取单个文章类目
exports.getCateById = (req, res) => {
  let { id } = req.params;
  let sqlStr = "select * from ev_article_cate where id = ? and is_delete = 0";
  db.query(sqlStr, id, (err, results) => {
    if (err) return rec.cc(err);
    if (results.length !== 1) {
      return res.cc("获取类目byId失败！", 0);
    }
    res.send({
      status: "0",
      message: "获取单个文章类目成功！",
      data: results[0],
    });
  });
};

// 根据ID更新文章分类
exports.updateCateById = (req, res) => {
  let { name, alias, id } = req.body;
  let sqlStr =
    "select * from ev_article_cate where id != ? and (name = ? or alias = ?)";
  db.query(sqlStr, [id, name, alias], (err, results) => {
    if (err) return res.cc(err);
    // 别名重复的情况可以写的更具体
    if (results.length === 1) {
      return res.send({
        status: "1",
        message: "分类名称或者别名重复！",
      });
    }
    // 发起修改的操作
    sqlStr = "update ev_article_cate set name = ?,alias = ? where id = ?";
    db.query(sqlStr, [name, alias, id], (err, results) => {
      console.log(results);
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) {
        return res.send({
          status: "1",
          message: "修改类目信息失败!",
        });
      }
      res.send({
        status: "0",
        message: "修改类目信息成功！",
        data: results,
      });
    });
  });
};
